using System;
using System.Diagnostics;

namespace SharpWars.Core.Tools
{
	public static class Timer
	{
		private static Stopwatch stopwatch = new Stopwatch();
		
		private static float elapsedTime = 0.0f;
		
		private static float runningTime = 0.0f;
		
		private static float fps = 0.0f;
		
		private static long lastTime = 0;
		
		private static long fpsUpdateInterval = Stopwatch.Frequency >> 1; 
		
		private static long lastFpsUpdate = 0;
		
		private static uint numFrames = 0;
		
		public static void Start()
		{
			stopwatch.Start();
		}
		
		public static void Stop()
		{
			stopwatch.Stop();
		}
		
		public static void Reset()
		{
			stopwatch.Reset();
		}
		
		public static void Update()
		{
			if( IsStarted )
			{
				long currentTime = stopwatch.ElapsedTicks;
				elapsedTime  = (float)( currentTime - lastTime ) / (float)Stopwatch.Frequency;
				runningTime += elapsedTime;
				
				numFrames++;
				if( currentTime - lastFpsUpdate >= fpsUpdateInterval )
				{
					float c = (float)currentTime / (float)Stopwatch.Frequency;
					float l = (float)lastFpsUpdate / (float)Stopwatch.Frequency;
				
					fps = (float)numFrames / (c - l);
					
					lastFpsUpdate = currentTime;
					numFrames = 0;
				}
				
				lastTime = currentTime;
			}
		}
		
		public static bool IsStarted
		{
			get
			{
				return stopwatch.IsRunning;
			}
		}
		
		public static float RunningTime
		{
			get
			{
				return runningTime;
			}
		}
		
		public static float ElaspedTime
		{
			get
			{
				return elapsedTime * 1000;
			}
		}
		
		public static float FPS
		{
			get
			{
				return fps;
			}
		}
	}
}
